package com.woniuxy.untis;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    @Value("woniuxy")
    private String secretKey;

    public String createJwt(int id, String account) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, 30);

        Map<String, Object> payload = new HashMap<String, Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);

        return JWTUtil.createToken(payload, secretKey.getBytes());
    }

    //解析令牌  获取userId
    public int getUserId(String token){
        JWT jwt = JWTUtil.parseToken(token);
        return ((NumberWithFormat) jwt.getPayload("id")).intValue();
    }
    //验证 token是否有效
    public Boolean validate(String token){
        return JWT.of(token).setKey(secretKey.getBytes()).verify();
    }
    //验证token是否过期
    public Boolean isExpice(String token){
        return JWT.of(token).setKey(secretKey.getBytes()).validate(0);
    }
}
